<template>
    <div class="search-container">
        <el-autocomplete
            ref="autocompleteRef"
            v-model="query"
            :fetch-suggestions="fetchSuggestions"
            :placeholder="`Search ${selectedTab}／Lineage／Gene`"
            @select="handleSelect"
            :trigger-on-focus="false"
            clearable
            :popper-class="'suggestions-dropdown'"
            class="w-full"
        >
            <template #prefix>
                <el-select
                    v-model="selectedTab"
                    size="small"
                    class="mr-2"
                    @change="handleTabChange"
                    style="width: 100px"
                >
                    <el-option label="Cellline" value="Cellline" />
                    <el-option label="Tissue" value="SampleType" />
                </el-select>
                <i class="el-icon-search"></i>
            </template>

            <!-- 自定义每条建议的渲染 -->
            <template #default="{ item }">
                <div v-if="item.isMore" class="autocomplete-more-item" @click.stop="handleMore(item.group)">
                    {{ item.count }} more {{ item.group }}, click to load more
                </div>
                <div v-else>
                    <el-tag type="info" size="small">{{ groupDict[item.group] }}</el-tag>
                    <span>{{ item.value }}</span>
                </div>
            </template>
        </el-autocomplete>
    </div>
</template>

<script setup lang="ts" name="EsSearchBar">
    import { ref, reactive, nextTick, watch } from 'vue';
    import type { AutocompleteInstance } from 'element-plus';
    import { get } from '../axios/api';
    import debounce from 'lodash.debounce';
    import { groupDict } from '@/common/util';

    // 用户输入
    const emit = defineEmits();
    const autocompleteRef = ref<AutocompleteInstance | null>(null);
    const props = defineProps({
        modelValue: {
            type: String,
            default: ''
        },
        tabValue: {
            type: String,
            default: 'Cellline'
        },
    });
    const query = ref(props.modelValue);

    watch(
        () => props.modelValue,
        (v) => {
            query.value = v
        },
        { immediate: true } // ← this makes it fire once immediately
    );
    const selectedTab = ref('Cellline');

    watch(() => props.tabValue, v => selectedTab.value = v,  { immediate: true })


    // 后端原始分组数据
    const results: any = ref({});
    // 标记哪些组已展开
    const expanded: any = reactive({
        cellline: false,
        sample_type: false,
        lineage: false,
        gene: false
    });
    // 给 el-autocomplete 回调的扁平化 suggestions
    const suggestions = ref([]);

    const tabLabels: Record<string, string> = {
        cellline: 'Cellline',
        sample_type: 'SampleType'
    };

    // 从后端拉取分组结果
    async function doSearch(val: any) {
        if (!val) {
            results.value = { cellline: [], sample_type: [], lineage: [], gene: [] };
            return;
        }
        try {
            const res = await get('/search/', { q: val });
            // 假设后端返回 { cellline: [...], sample_type: [...], lineage: [...], gene: [...] }
            results.value = res;
        } catch (err) {
            console.error(err);
        }
    }

    // 根据 results 和 expanded，构造 suggestions
    function buildSuggestions() {
        const list: any = [];

        const groups =
            selectedTab.value === 'Cellline' ? ['cellline', 'lineage', 'gene'] : ['sample_type', 'lineage', 'gene'];

        groups.forEach(grp => {
            const arr = results.value[grp] || [];
            if (!arr.length) return;
            if (expanded[grp]) {
                // 展开：全列表
                arr.forEach((v: any) => list.push({ group: grp, value: v, isMore: false }));
            } else {
                // 未展开：前3 + “更多”行
                const head3 = arr.slice(0, 3).map((v: any) => ({ group: grp, value: v, isMore: false }));
                list.push(...head3);
                if (arr.length > 3) {
                    list.push({
                        group: grp,
                        isMore: true,
                        count: arr.length - 3
                    });
                }
            }
        });

        suggestions.value = list;
    }

    // 防抖包装 fetchSuggestions
    const fetchSuggestions = debounce(async (val: any, cb: any) => {
        await doSearch(val);
        // 每次搜索都重置所有分组为未展开
        // Object.keys(expanded).forEach(k => (expanded[k] = false));
        buildSuggestions();
        // 最终回调给 el-autocomplete
        cb(suggestions.value);
    }, 300);

    // 点击“展开”后的处理
    const handleMore = async (group: any) => {
        expanded[group] = true;
        if (autocompleteRef.value) {
            // 需要确保下拉菜单保持打开状态，以便 getData 刷新它。
            // 如果下拉菜单自动关闭，可能需要重新打开它。
            // 目前，假设它保持打开或 getData 隐式处理。
            autocompleteRef.value.getData(query.value); // 使用当前查询调用 getData
        }
    };

    // 选中建议时
    function handleSelect(item: any) {
        // item 是建议对象，本例直接把字符串填回输入框
        if (!item.value) return; // 点了更多行，啥也不做
        emit('select', { tab: selectedTab.value, group: item.group, value: item.value });
        query.value = item.value;
        emit('update:modelValue', query.value);
    }

    function handleTabChange(val: any) {
        // notify parent
        query.value = '';
        suggestions.value = [];
        results.value = { cellline: [], sample_type: [], lineage: [], gene: [] };
        Object.keys(expanded).forEach(k => (expanded[k] = false));
        autocompleteRef.value?.blur();
        emit('tab', { type: selectedTab.value, query: query.value });
    }
</script>

<style scoped>
    .search-container {
        max-width: 100%;
        margin: 0 auto;
    }
    .suggestions-dropdown .el-autocomplete-suggestion__wrap {
        max-height: 300px;
        overflow: auto;
    }
    .suggestion-item {
        display: flex;
        align-items: center;
        padding: 4px 8px;
        cursor: pointer;
    }
    .group-tag {
        margin-right: 6px;
        text-transform: capitalize;
    }
    .item-label {
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
    }
    .autocomplete-more-item {
        width: 100%;
        color: #409eff;
        /* text-align: center; */
        font-style: italic;
    }
</style>
